package org.oslo.mule.service;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.oslo.domain.ImageInfo;
import org.oslo.domain.SearchInfo;

import com.aetrion.flickr.Flickr;
import com.aetrion.flickr.photos.Photo;
import com.aetrion.flickr.photos.PhotoList;
import com.aetrion.flickr.photos.SearchParameters;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class FlickrService {
	
	public ArrayList<ImageInfo> getImageFromFlickr(SearchInfo searchInfo) {

    	ArrayList<ImageInfo> imageList = new ArrayList<ImageInfo>(); 
        try {
            Flickr flickr = new com.aetrion.flickr.Flickr("c3630385233916b61c6a8c214a74c26e");
            SearchParameters searchParam = new SearchParameters();
            searchParam.setTags(new String[]{searchInfo.getConferenceName()});
            searchParam.setSort(SearchParameters.RELEVANCE);	
            searchParam.setExtras(true);
            long start = System.currentTimeMillis();
            PhotoList searchResult = flickr.getPhotosInterface().search(searchParam, searchInfo.getImageCount(), 0);
            System.out.println("Time: " + (System.currentTimeMillis() - start));
            
            for (int i = 0 ; i < searchResult.size() ; i++) {
            	start = System.currentTimeMillis();
            	Photo photo = (Photo) searchResult.get(i);
            	try {
            		byte[] jpgStream = getImageData(photo.getMediumImage());            	
            		System.out.println("Time - photo: " + (System.currentTimeMillis() - start));	
                	ImageInfo imageInfo = new ImageInfo();
                	imageInfo.setImageData(jpgStream);
                	imageInfo.setDescription(photo.getDescription());
                	imageInfo.setUser(photo.getOwner().getRealName());
                	imageList.add(imageInfo);
            		
				} catch (Exception e) {
					// sometimes errors occur here
					e.printStackTrace();
					System.out.println("Skipping erronous image");
				}
            }
        } catch (Exception ex) {
            Logger.getLogger("global").log(Level.SEVERE, null, ex);
        } 
        return imageList;
    }
	
	private static byte[] getImageData(BufferedImage myImage) throws IOException {
		ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bOut);
        encoder.encode(myImage);
        byte[] result = bOut.toByteArray();
        bOut.close();
        return result;
	}
}
